import axios from 'axios';
import axiosConfig from './config'; // axios请求配置
import apiArr from './api'; // 用户请求集合
import qs from 'qs';
import { Message } from 'element-ui';

// 创建axios实例
const service = axios.create({
  baseURL: axiosConfig.baseURL,
  timeout: axiosConfig.timeout,
  headers: axiosConfig.headers
});

// 添加请求拦截器
service.interceptors.request.use(function (config) {
  //  promise动态添加请求头，加完之后再return出config继续请求
  const headerHandlers = (axiosConfig.headerHandlers || []).map(handler => {
    return handler(config).then((mixHeaders) => Object.assign(config.headers || {}, mixHeaders))
  });
  return Promise.all(headerHandlers).then(() => config);
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
service.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  if (response.status !== 200) {
    Promise.reject('network error')
    return
  }
  // 未设置状态码则默认成功状态
  const { code, msg } = response.data
  // 二进制数据则直接返回
  if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
    return response
  }
  return response.data;
}, function (error) {
  // 对响应错误做点什么
  let { message } = error
  // 对响应错误做点什么
  if (message == 'Network Error') {
    message = '后端接口连接异常'
  } else if (message.includes('timeout')) {
    message = '系统接口请求超时'
  } else if (message.includes('Request failed with status code 429')) {
    message = '请求过于频繁，请稍后再试'
  } else if (message.includes('Request failed with status code')) {
    message = '系统接口' + message.substr(message.length - 3) + '异常'
  }
  Message({
    message: message,
    type: 'error',
    duration: 2 * 1000,
  })
  //return Promise.reject(error)
});

// 创建请求
const USE_DATA_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];
const createRequest = () => {
  const hostApi = {};
  apiArr.forEach(api => {
    hostApi[api.name] = (params) => {
      const method = api.method || "POST";
      const requestParams = USE_DATA_METHODS.includes(method) ? { data: qs.stringify(params) } : { params: params };
      return service({
        url: api.path,
        method,
        headers: {
          ...api.headers
        },
        ...requestParams,
      })
    }
  });
  return hostApi;
}

const apis = createRequest();

export default apis;
